package com.rzico.sbl.ui.report.manager

import android.widget.TextView
import com.github.mikephil.charting.data.BarEntry
import com.github.mikephil.charting.formatter.IAxisValueFormatter
import com.github.mikephil.extend.CustomValueFormatter
import com.github.mikephil.extend.setChartValueSelectedListener
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportPayoutBinding
import com.rzico.sbl.model.ManagerDate
import com.rzico.sbl.model.ManagerGoodsData
import com.rzico.sbl.model.ManagerWayModel
import com.rzico.sbl.other.*
import com.rzico.sbl.viewmodel.ReportPayoutViewModel
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.helper.floatValue
import com.xinnuo.common.helper.toFormat
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.utils.showTimeRangeDialog

class ReportPayoutActivity : BaseActivity(R.layout.activity_report_payout) {

    private val mBinding by lazy { ActivityReportPayoutBinding.bind(getRootView()) }

    private var mBeginDate = getBeforeDate(6)
    private var mEndDate = getTodayDate()
    private var mChartModel: ManagerWayModel? = null

    // 水票抵扣
    private val mTicketList = ArrayList<ManagerGoodsData>()
    private val mTicketRange = ArrayList<ManagerDate>()
    private var mBrandTicketSn = ""

    // 免单
    private val mFreeList = ArrayList<ManagerGoodsData>()
    private val mFreeRange = ArrayList<ManagerDate>()
    private var mBrandFreeSn = ""

    // 漏桶
    private val mSwapList = ArrayList<ManagerGoodsData>()
    private val mSwapRange = ArrayList<ManagerDate>()
    private var mBrandSwapSn = ""

    // 退桶
    private val mBackList = ArrayList<ManagerGoodsData>()
    private val mBackRange = ArrayList<ManagerDate>()
    private var mBrandBackSn = ""

    override fun getViewModel() = get<ReportPayoutViewModel>()

    override fun initData() {
        initTitle(title = "支出", name = "近7天")

        initLayout()

        updateAllData()
    }

    private fun initLayout() {
        mBinding.also {
            it.payoutTicket1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTicketList.indices) ""
                    else mTicketList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mBrandTicketSn = mTicketList[index].name
                        mBinding.payoutTicketTitle.text = mTicketList[index].name
                        getBrandRangeData("exchangePrice")
                    }
                }
            }

            it.payoutTicket2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mTicketRange.indices) ""
                    else mTicketRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.payoutCoupon.apply {
                initChart(
                    isCenterLabel = true,
                    isXGridLine = true,
                    isYGridLine = false,
                    xAxisMinimum = 0f,
                    yAxisMinimum = 0f,
                    xSpaceEntry = 20f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (
                        mChartModel == null
                        || value.toInt() !in mChartModel!!.coupon.indices
                    ) ""
                    else
                        mChartModel!!.coupon[value.toInt()]
                            .date
                            .toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.payoutMian1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mFreeList.indices) ""
                    else mFreeList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mBrandFreeSn = mFreeList[index].name
                        mBinding.payoutMianTitle.text = mFreeList[index].name
                        getBrandRangeData("free")
                    }
                }
            }

            it.payoutMian2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mFreeRange.indices) ""
                    else mFreeRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.payoutLou1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mSwapList.indices) ""
                    else mSwapList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mBrandSwapSn = mSwapList[index].name
                        mBinding.payoutLouTitle.text = mSwapList[index].name
                        getBrandRangeData("swap")
                    }
                }
            }

            it.payoutLou2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mSwapRange.indices) ""
                    else mSwapRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }

            it.payoutTui1.apply {
                initChart(
                    isLegend = false,
                    touchDistance = 10f,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mBackList.indices) ""
                    else mBackList[value.toInt()].name.run {
                        if (length > 4) "${substring(0, 3)}..." else this
                    }
                }

                // 添加点击事件
                setChartValueSelectedListener {
                    onValueSelected { entry, _ ->
                        val index = entry.x.toInt()

                        mBrandBackSn = mBackList[index].name
                        mBinding.payoutTuiTitle.text = mBackList[index].name
                        getBrandRangeData("refunds")
                    }
                }
            }

            it.payoutTui2.apply {
                initChart(
                    isLegend = false,
                    xLabelAngle = -45f,
                    yAxisMinimum = 0f
                )

                // 格式化x轴文本显示
                xAxis.valueFormatter = IAxisValueFormatter { value, _ ->
                    return@IAxisValueFormatter if (value.toInt() !in mBackRange.indices) ""
                    else mBackRange[value.toInt()].date.toFormat("yyyy-MM-dd", "M.d")
                }
            }
        }

        tvRight?.oneClick { text ->
            text as TextView

            getViewModel()
                .showDropTimeFilter(
                    context = getIContext(),
                    bottom = text,
                    list = getViewModel().mTimeCheckList
                ) { bean ->

                    (bean.id != "4")
                        .condition {
                            getViewModel().mTimeCheckList.last().name = "自定义时间"
                        }

                    when (bean.id) {
                        "1" -> {
                            mBeginDate = getBeforeDate(6)
                            mEndDate = getTodayDate()
                            text.text = "近7天"

                            updateAllData()
                        }
                        "2" -> {
                            mBeginDate = getFirstDate()
                            mEndDate = getEndDate()
                            text.text = "本月"

                            updateAllData()
                        }
                        "3" -> {
                            mBeginDate = getBeforeFirstDate()
                            mEndDate = getBeforeEndDate()
                            text.text = "上月"

                            updateAllData()
                        }
                        "4" -> {
                            showTimeRangeDialog(
                                minYearValue = 2021,
                                isCurrentDate = true,
                                isAfterLimited = true,
                                onResult = { start, end ->
                                    getViewModel()
                                        .mTimeCheckList
                                        .forEach { it.isChecked = false }

                                    getViewModel()
                                        .mTimeCheckList
                                        .last()
                                        .isChecked = true

                                    mBeginDate = start
                                    mEndDate = end
                                    text.text = "自定义时间"
                                    bean.name = "$mBeginDate ~ $mEndDate"

                                    updateAllData()
                                }
                            )
                        }
                    }
                }
        }
    }

    /**
     * 设置所有品牌销量
     */
    private fun setBrandChart(type: String) {
        mBinding.also { layout ->
            when (type) {
                "exchangePrice" -> {
                    layout
                        .payoutTicket1
                        .apply {
                            if (mTicketList.isEmpty()) {
                                clear()
                                mBinding.payoutTicket2.clear()
                                mBinding.payoutTicketTitle.text = "暂无品牌"
                            } else {
                                setSingleData(
                                    entries = mTicketList.mapIndexed { index, data ->
                                        BarEntry(index.toFloat(), data.amount.toFloat())
                                    },
                                    colorList = getViewModel().brandColor(),
                                    formatter = CustomValueFormatter()
                                )
                            }

                            animateY(500)
                        }
                }
                "free" -> {
                    layout
                        .payoutMian1
                        .apply {
                            if (mFreeList.isEmpty()) {
                                clear()
                                mBinding.payoutMian2.clear()
                                mBinding.payoutMianTitle.text = "暂无品牌"
                            } else {
                                setSingleData(
                                    entries = mFreeList.mapIndexed { index, data ->
                                        BarEntry(index.toFloat(), data.amount.toFloat())
                                    },
                                    colorList = getViewModel().brandColor(),
                                    formatter = CustomValueFormatter()
                                )
                            }

                        animateY(500)
                    }
                }
                "swap" -> {
                    layout
                        .payoutLou1
                        .apply {
                            if (mSwapList.isEmpty()) {
                                clear()
                                mBinding.payoutLou2.clear()
                                mBinding.payoutLouTitle.text = "暂无品牌"
                            } else {
                                setSingleData(
                                    entries = mSwapList.mapIndexed { index, data ->
                                        BarEntry(index.toFloat(), data.amount.toFloat())
                                    },
                                    colorList = getViewModel().brandColor(),
                                    formatter = CustomValueFormatter()
                                )
                            }

                        animateY(500)
                    }
                }
                "refunds" -> {
                    layout
                        .payoutTui1
                        .apply {
                            if (mBackList.isEmpty()) {
                                clear()
                                mBinding.payoutTui2.clear()
                                mBinding.payoutTuiTitle.text = "暂无品牌"
                            } else {
                                setSingleData(
                                    entries = mBackList.mapIndexed { index, data ->
                                        BarEntry(index.toFloat(), data.amount.toFloat())
                                    },
                                    colorList = getViewModel().brandColor(),
                                    formatter = CustomValueFormatter()
                                )
                            }

                        animateY(500)
                    }
                }
            }
        }
    }

    /**
     * 设置单个品牌最近销量
     */
    private fun setBrandRangeChart(type: String) {
        when (type) {
            "exchangePrice" -> {
                mBinding
                    .payoutTicket2
                    .apply {
                        setSingleData(
                            entries = mTicketRange.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.amount.toFloat())
                            },
                            colorList = listOf(
                                getViewModel()
                                    .brandColor()[
                                        mTicketList.indexOfFirst { it.name == mBrandTicketSn } % 24
                                    ]
                            ),
                            isHighlight = false,
                            formatter = CustomValueFormatter()
                        )

                        animateY(500)
                    }
            }
            "free" -> {
                mBinding
                    .payoutMian2
                    .apply {
                        setSingleData(
                            entries = mFreeRange.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.amount.toFloat())
                            },
                            colorList = listOf(
                                getViewModel()
                                    .brandColor()[
                                        mFreeList.indexOfFirst { it.name == mBrandFreeSn } % 24
                                    ]
                            ),
                            isHighlight = false,
                            formatter = CustomValueFormatter()
                        )

                        animateY(500)
                    }
            }
            "swap" -> {
                mBinding
                    .payoutLou2
                    .apply {
                        setSingleData(
                            entries = mSwapRange.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.amount.toFloat())
                            },
                            colorList = listOf(
                                getViewModel()
                                    .brandColor()[
                                        mSwapList.indexOfFirst { it.name == mBrandSwapSn } % 24
                                    ]
                            ),
                            isHighlight = false,
                            formatter = CustomValueFormatter()
                        )

                        animateY(500)
                    }
            }
            "refunds" -> {
                mBinding
                    .payoutTui2
                    .apply {
                        setSingleData(
                            entries = mBackRange.mapIndexed { index, data ->
                                BarEntry(index.toFloat(), data.amount.toFloat())
                            },
                            colorList = listOf(
                                getViewModel()
                                    .brandColor()[
                                        mBackList.indexOfFirst { it.name == mBrandBackSn } % 24
                                    ]
                            ),
                            isHighlight = false,
                            formatter = CustomValueFormatter()
                        )

                        animateY(500)
                    }
            }
        }
    }

    /**
     * 设置优惠券柱状图数据
     */
    private fun setCouponChart() {
        mBinding
            .payoutCoupon
            .apply {
                if (mChartModel != null && (
                            !mChartModel?.coupon.isNullOrEmpty()
                                    || !mChartModel?.coupon2.isNullOrEmpty()
                                    || !mChartModel?.coupon3.isNullOrEmpty()
                            )
                ) {
                    setGroupData(
                        entries = arrayListOf(
                            mChartModel!!.coupon.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.amount.floatValue
                                )
                            },
                            mChartModel!!.coupon2.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.amount.floatValue
                                )
                            },
                            mChartModel!!.coupon3.mapIndexed { index, data ->
                                BarEntry(
                                    index.toFloat(),
                                    data.amount.floatValue
                                )
                            }
                        ),
                        colorList = getViewModel().color1(),
                        labelList = listOf("优惠券(一)", "优惠券(二)", "优惠券(三)"),
                        xFromValue = 0f,
                        formatter = CustomValueFormatter()
                    )
                } else clear()

                animateY(500)
            }
    }

    /**
     * 获取所有品牌销量
     */
    private fun getBrandListData(type: String) {
        getViewModel()
            .brandList(
                type = type,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { list ->
                    when (type) {
                        "exchangePrice" -> {
                            mTicketList.clear()
                            mTicketList.addItems(list)

                            if (mTicketList.isNotEmpty()) {
                                if (mTicketList.none { it.name == mBrandTicketSn }) {
                                    mBrandTicketSn = mTicketList[0].name
                                    mBinding.payoutTicketTitle.text = mTicketList[0].name
                                }
                                getBrandRangeData(type)
                            }
                        }
                        "free" -> {
                            mFreeList.clear()
                            mFreeList.addItems(list)

                            if (mFreeList.isNotEmpty()) {
                                if (mFreeList.none { it.name == mBrandFreeSn }) {
                                    mBrandFreeSn = mFreeList[0].name
                                    mBinding.payoutMianTitle.text = mFreeList[0].name
                                }
                                getBrandRangeData(type)
                            }
                        }
                        "swap" -> {
                            mSwapList.clear()
                            mSwapList.addItems(list)

                            if (mSwapList.isNotEmpty()) {
                                if (mSwapList.none { it.name == mBrandSwapSn }) {
                                    mBrandSwapSn = mSwapList[0].name
                                    mBinding.payoutLouTitle.text = mSwapList[0].name
                                }
                                getBrandRangeData(type)
                            }
                        }
                        "refunds" -> {
                            mBackList.clear()
                            mBackList.addItems(list)

                            if (mBackList.isNotEmpty()) {
                                if (mBackList.none { it.name == mBrandBackSn }) {
                                    mBrandBackSn = mBackList[0].name
                                    mBinding.payoutTuiTitle.text = mBackList[0].name
                                }
                                getBrandRangeData(type)
                            }
                        }
                    }

                    setBrandChart(type)
                }
            )
    }

    /**
     * 获取单个品牌最近销量
     */
    private fun getBrandRangeData(type: String) {
        getViewModel()
            .brandRangeList(
                type = type,
                barrel = when (type) {
                    "exchangePrice" -> mBrandTicketSn
                    "free" -> mBrandFreeSn
                    "swap" -> mBrandSwapSn
                    "refunds" -> mBrandBackSn
                    else -> ""
                },
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    when (type) {
                        "exchangePrice" -> {
                            mTicketRange.clear()
                            mTicketRange.addItems(it)
                        }
                        "free" -> {
                            mFreeRange.clear()
                            mFreeRange.addItems(it)
                        }
                        "swap" -> {
                            mSwapRange.clear()
                            mSwapRange.addItems(it)
                        }
                        "refunds" -> {
                            mBackRange.clear()
                            mBackRange.addItems(it)
                        }
                    }

                    setBrandRangeChart(type)
                }
            )
    }

    /**
     * 获取优惠券柱状图数据
     */
    private fun getCouponData() {
        getViewModel()
            .payCouponList(
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = { data ->
                    mChartModel = data

                    setCouponChart()
                }
            )
    }

    /**
     * 刷新所有数据
     */
    private fun updateAllData() {
        getBrandListData("exchangePrice")
        getCouponData()
        getBrandListData("free")
        getBrandListData("swap")
        getBrandListData("refunds")
    }

}